#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<string>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<cstring>
#include<unistd.h>

using namespace std;
int main()
{
    int fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd < 0)
    {
        cout << "socket error" << endl;
    }
    int port = 8080;
    string ip = "0.0.0.0";
    struct sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = ntohs(port);
    local.sin_addr.s_addr = inet_addr(ip.c_str());
    int n = bind(fd, (struct sockaddr*)&local, sizeof(local));
    socklen_t len = sizeof(local);
    if (n < 0)
    {
        cout << "bind failed" << endl;
        return 1;
    }
    while (true)
    {
        char buffer[1024];
        ssize_t n = recvfrom(fd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&local, &len);


        if (n < 0)
        {
            cout << "recvfrom failed: " << endl;
        }
        else if (n == 0)
        {
            cout << "client closed,me too!" << endl;
            close(fd);
            return 0;
        }
        else
        {
            cout << "server recv: " << buffer << endl;
        }
        ssize_t b = sendto(fd, buffer, sizeof(buffer), 0, (struct sockaddr*)&local, len);
        if (b < 0)
        {
            cout << "sendto failed" << endl;
            return 1;
        }
        else if (b == 0)
        {
            cout << "client close,me too!" << endl;
            returnz 0;
        }
        else
        {
            cout << "server recv: " << buffer << endl;
        }
    }
    return 0;
}